package achi.community.irla.beans;

import achi.community.irla.database.Crypto;
import achi.community.irla.database.DatabaseImpl;
import achi.community.irla.database.ModelBean;
import achi.community.irla.entities.Users;
import com.icesoft.faces.context.effects.Effect;
import com.icesoft.faces.context.effects.Highlight;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import java.lang.String;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.application.ViewHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.event.FacesEvent;
import javax.faces.event.ValueChangeEvent;
import javax.faces.validator.ValidatorException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * RegControlBean:
 * Validation for register.xhtml
 * Adds the new Customer to DB and ModelBean
 */
@ManagedBean
@RequestScoped
public class LoginControlBean implements Serializable {

    @EJB
    DatabaseImpl db;
    @ManagedProperty(value = "#{loginBackBean}")
    LoginBackBean backingBean;
    @ManagedProperty(value = "#{modelBean}")
    ModelBean modelBean;

    public void setModelBean(ModelBean modelBean) {
        this.modelBean = modelBean;
    }

    public ModelBean getModelBean() {
        return modelBean;
    }

    public LoginBackBean getBackingBean() {
        return backingBean;
    }

    public void setBackingBean(LoginBackBean backingBean) {
        this.backingBean = backingBean;
    }

    public void viewCheckName(ValueChangeEvent event) {
        //System.out.println("viewCheckName!");
        String input = event.getNewValue().toString();
        //  System.out.println("viewCheckName!: "+input);
        String id = event.getComponent().getClientId();
        checkName(input, id);
    }

    public void viewCheckPassword(ValueChangeEvent event) {
        String input = event.getNewValue().toString();
        String id = event.getComponent().getClientId();
        checkPassword(input, id);
    }

    public void viewCheckEmail(ValueChangeEvent event) {
        String input = event.getNewValue().toString();
        String id = event.getComponent().getClientId();
        // checkEmail(input, id);
    }

    public void checkPassword(String input, String id) {
        if (!checkLength(input, 3, 20)) {
            putMessage(id, "fields.error.password");
        }
    }

    public boolean checkLength(String input, int min, int max) {
        int length = input.length();
        if (length > min && length < max) {
            return true;
        } else {
            return false;
        }
    }

    public boolean checkLetters(String input) {
        int count = 0;
        int length = input.length();
        while (count < length && Character.isLetter(input.charAt(count))) {
            count++;
        }
        if (count < length) {
            //putMessage(id, "fields.error.letters");
            return false;
        } else {
            return true;
        }
    }

    public boolean checkName(String input, String id) {
        if (checkLength(input, 0, 20)) {
            if (!checkLetters(input)) {
                putMessage(id, "fields.error.letters");
                return false;
            }
        } else {
            putMessage(id, "fields.error.required");
            return false;
        }
        return true;
    }

    public void letterDigitBlank(FacesContext context, UIComponent component, Object value) {
        String input = value.toString();

        if (input.length() > 1) {
            for (int i = 0; i < input.length(); i++) {
                if (!Character.isLetterOrDigit(input.charAt(i)) && input.charAt(i) != ' ') {
                    FacesMessage msg = new FacesMessage("only normal chars");
                    throw new ValidatorException(msg);
                }
            }
        } else {
            FacesMessage msg = new FacesMessage("Required field");
            throw new ValidatorException(msg);
        }
    }

    public void onlyLetter() {
        System.out.println("onlyLetters!!");
        /**
        //ValueChangeEvent event) {
        if(event!=null){
        String input = event.getNewValue().toString();
        String id = event.getComponent().getClientId();

        int length = input.length();
        if (length > 1) {
        int count = 0;
        while (count < length && Character.isLetter(input.charAt(count))) {
        count++;
        }
        if (count < length) {
        putMessage(id, "fields.error.letters");
        fieldOk = false;
        } else {
        fieldOk = true;
        }
        /**
        for (int i = 0; i < input.length() && Character.isLetter(input.charAt(i)); i++) {
        if (!Character.isLetter(input.charAt(i))) {
        putMessage(id, "fields.error.letters");
        fieldOk = false;
        }
        else
        fieldOk = true;
        }
         * */
        /**
        } else {
        putMessage(id, "fields.error.required");
        fieldOk = false;
        }
        }
        else
        fieldOk=true;
        //checkFields();
         * */
    }

    public void checkFields() {
        /**
        if(fieldOk){
        FacesContext context = FacesContext.getCurrentInstance();
        UIComponent btn = context.getViewRoot().findComponent("btnRegister");
        CommandButton b = (CommandButton)btn;

        CommandButton a;

        UIViewRoot root = context.getViewRoot();
        }
         */
    }

    public void putMessage(String id, String key) {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("MessageBoundle", FacesContext.getCurrentInstance().getViewRoot().getLocale());
        String value = resourceBundle.getString(key);
        FacesMessage msg = new FacesMessage(value);
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(id, msg);
    }

    public String getClientId(String id) {
        FacesContext context = FacesContext.getCurrentInstance();
        UIViewRoot root = context.getViewRoot();
        return findComponent(root, id).getClientId();
    }

    /**
     * Finds component with the given id
     */
    private UIComponent findComponent(UIComponent c, String id) {
        if (id.equals(c.getId())) {
            return c;
        }
        Iterator<UIComponent> kids = c.getFacetsAndChildren();
        while (kids.hasNext()) {
            UIComponent found = findComponent(kids.next(), id);
            if (found != null) {
                return found;
            }
        }
        return null;
    }

    /**
    public void onlyLetter(FacesContext context, UIComponent validate, Object value)
    {
    //FacesMessage msg = new FacesMessage("Required field");
    // context.addMessage(validate.getClientId(context), msg);
    //throw new ValidatorException(msg);

    String input = value.toString();
    if( input.length() > 1)
    {
    for(int i = 0; i < input.length(); i++)
    if (!Character.isLetter(input.charAt(i)))
    {
    FacesMessage msg = new FacesMessage("Field must be letters");
    throw new ValidatorException(msg);
    }
    }
    else
    {
    FacesMessage msg = new FacesMessage("Required field");
    throw new ValidatorException(msg);
    }

    }
     */
    public String buttonClicked() {//ActionEvent evt) {
        String mail = backingBean.getEmail();

        if (db.userExists(mail)) {
            Users user = db.getUser2(mail);
            String pas = user.getPassword();

            String in_pas = backingBean.getPassword();
            try {
                in_pas = Crypto.byteArrayToHexString(Crypto.computeHash(in_pas));
            } catch (Exception e) {
                return "error";
            }
            if (pas.equals(in_pas)) {
                modelBean.setUser(user);
                return "news";
            } else {
                //System.out.println(user.toString());
                String id = getClientId("TxtPassword");
                putMessage(id, "fields.error.password2");
            }
        } else {
            //System.out.println("Finns ej");
            String id = getClientId("TxtEmail");
            putMessage(id, "fields.error.email2");
        }

        return "login";
        /**
        String id1 = getClientId("TxtEmail");
        String id2 = getClientId("TxtPassword");
        if(user != null){
        putMessage(id1, "fields.error.required");
        }
        else{
        putMessage(id2, "fields.error.required");
        }
         */
    }

    public String popupAccept() {
        // String firstname = backingBean.getFirstname();
        // String lastname = backingBean.getLastname();
        String email = backingBean.getEmail();
        // String username = backingBean.getUsername();
        String password = backingBean.getPassword();

        // Users user = new Users(firstname, lastname, email, username, password, null);
        //  user.setEmail(backingBean.getEmail());
        //  db.addUser(user);
        //  modelBean.setUser(user);

        return "news";
    }

    public void update() {
        FacesContext context = FacesContext.getCurrentInstance();
        String viewId = context.getViewRoot().getViewId();
        ViewHandler handler = context.getApplication().getViewHandler();
        UIViewRoot root = handler.createView(context, viewId);
        root.setViewId(viewId);
        context.setViewRoot(root);
    }
}
